package com.meego.common.oembed;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

public class DefaultOembedProvider implements OembedProvider {
	private String name;
	private String endpoint;
	private String format;
	private Integer maxWidth;
	private Integer maxHeight;
	private List<String> urlSchemes;
	private Map<String, String> extra = new HashMap<String, String>();
		
    @Override
	public URI toApiUrl(final String url) throws URISyntaxException {
		String uri = null;
		final List<NameValuePair> query = new ArrayList<NameValuePair>();

		if(this.getEndpoint().toLowerCase().contains("%{format}"))
			uri = this.getEndpoint().replaceAll(Pattern.quote("%{format}"), this.getFormat());
		else {
			uri = this.getEndpoint();
			query.add(new BasicNameValuePair("format", this.getFormat()));
		}
		query.add(new BasicNameValuePair("url", url));
		if(this.getMaxWidth() != null)
			query.add(new BasicNameValuePair("maxwidth", this.getMaxWidth().toString()));
		if(this.getMaxHeight() != null)
			query.add(new BasicNameValuePair("maxheight", this.getMaxHeight().toString()));
		for (Entry<String, String> entry : extra.entrySet()) {
			query.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		return new URI(String.format("%s?%s", uri, URLEncodedUtils.format(query, "UTF-8")));
	}
	
	public void addExtraParam(String key, String value) {
		this.extra.put(key, value);
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getEndpoint() {
		return endpoint;
	}
	
	public void setEndpoint(String apiEndpoint) {
		this.endpoint = apiEndpoint;
	}
	
	public List<String> getUrlSchemes() {
		return urlSchemes;
	}
	
	public void setUrlSchemes(List<String> urlSchemes) {
		this.urlSchemes = urlSchemes;
	}

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

	public Integer getMaxWidth() {
		return maxWidth;
	}

	public void setMaxWidth(Integer maxWidth) {
		this.maxWidth = maxWidth;
	}

	public Integer getMaxHeight() {
		return maxHeight;
	}

	public void setMaxHeight(Integer maxHeight) {
		this.maxHeight = maxHeight;
	}
}